//
//  MapDirectionsViewController.m
//  MapDirections
//
//  Created by KISHIKAWA Katsumi on 09/08/10.
//  Copyright 2009 KISHIKAWA Katsumi. All rights reserved.
//

#import "MapDirectionsViewController.h"
#import "UICRouteOverlayMapView.h"
#import "UICRouteAnnotation.h"

@implementation MapDirectionsViewController

- (id)initWithEndPoint:(MyAnnotation *)point
{
	self = [super init];
	if(nil != self)
	{
		endPoint = point;
		[endPoint retain];
		n = 0;
	}
	
	return self;
}

- (void)dealloc
{ 
	state = NO;
	[alertView release];
	
	routeMapView.delegate = nil;
	routeMapView.showsUserLocation = NO;
	[routeMapView removeAnnotations:routeMapView.annotations];
	[routeMapView release];
	
	/*
	diretions.delegate = nil;
	[diretions release];
	diretions = nil;
	*/
	
	diretions = nil;
	[diretions release];
	
	routeOverlayView = nil;
	[routeOverlayView release];
	
	endPoint = nil;
	[endPoint release];
	
	//[centerButton release];
    [super dealloc];
}

- (void)loadView {
	self.title = @"Cómo llegar";
	
	UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 450.0f)];
	self.view = contentView;
	[contentView release];
	
	routeMapView = [[[MKMapView alloc] initWithFrame:contentView.frame] retain];
	routeMapView.delegate = self;
	routeMapView.showsUserLocation = NO;
	MKCoordinateRegion region;
	MKCoordinateSpan span;
	span.latitudeDelta=0.1;
	span.longitudeDelta=0.1;
	
	CLLocationCoordinate2D location = {41.641184, -0.894032};
	region.span=span;
	region.center=location;
	
	[routeMapView setRegion:region];
	
	[contentView addSubview:routeMapView];
	//[routeMapView release];
	state = YES;
	routeOverlayView = [[[UICRouteOverlayMapView alloc] initWithMapView:routeMapView] retain];
}

- (void) observeValueForKeyPath: (NSString *) keyPath
                       ofObject: (id) object
                         change: (NSDictionary *) change
                        context: (void *) context
{
	if (keyPath == @"location")
	{
		for (id item in change)
		{
			id value = [change objectForKey:item];
			if ([value isKindOfClass: [CLLocation class]]) 
			{
				
				n++;
				if (n == 2) 
				{
					[self update];
				}
			}
		}	
	}
}

- (void)viewDidLoad {
    [super viewDidLoad];
	[self setSearchingModeEnabled:YES];
	diretions = [[UICGDirections sharedDirections] retain];
	[diretions setDelegate:self];
	
#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 30200)
	
    NSString *str;
	
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        str = [NSString stringWithString:@"Running as an iPad application"];
		
		routeMapView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    } 	
    
	
#endif    
    
    [super viewDidLoad];
	
	[routeMapView.userLocation addObserver:self forKeyPath:@"location"
					  options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial
					  context:nil];

	routeMapView.delegate = self;
	
	if (!routeMapView.showsUserLocation) {
		routeMapView.showsUserLocation = YES;
	}
	
	centerButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"locatePin.png"]
																  style:UIBarButtonItemStyleBordered 
																 target:self 
																 action:@selector(moveToUserLocation)];
	self.navigationItem.rightBarButtonItem = centerButton;
	if (diretions.isInitialized) {
		[self update];
	}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)update {
	
	//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
	
	UICGDirectionsOptions *options = [[[UICGDirectionsOptions alloc] init] autorelease];
	options.travelMode = UICGTravelModeWalking;
	NSString *endPointCoord = [[NSString alloc] initWithFormat:@"%f,%f", endPoint.coordinate.latitude, endPoint.coordinate.longitude];
	double lat = routeMapView.userLocation.coordinate.latitude;
	double lon = routeMapView.userLocation.coordinate.longitude;
	NSString *startPointCoord = [[NSString alloc] initWithFormat:@"%f,%f", lat, lon]; // @"41.632938,-0.874220";
	[diretions loadWithStartPoint:startPointCoord endPoint:endPointCoord options:options];
	[endPointCoord release];
	[startPointCoord release];
	NSLog(@"end update");
	[self setSearchingModeEnabled:NO];
	//[pool release];
}

- (void)moveToUserLocation {
	[routeMapView setCenterCoordinate:[routeMapView.userLocation coordinate] animated:YES];
}

- (void)addPinAnnotation:(id)sender 
{
	UICRouteAnnotation *pinAnnotation = [[[UICRouteAnnotation alloc] initWithCoordinate:[routeMapView centerCoordinate]
																				  title:nil
																		 annotationType:UICRouteAnnotationTypeWayPoint] autorelease];
	[routeMapView addAnnotation:pinAnnotation];
}

#pragma mark <UICGDirectionsDelegate> Methods

- (void)directionsDidFinishInitialize:(UICGDirections *)directions {
	n++;
	if (n == 2) {
		[self update];
	}
}

- (void)directions:(UICGDirections *)directions didFailInitializeWithError:(NSError *)error {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	
	alertView = [[UIAlertView alloc] initWithTitle:@"Direcciones" message:[error localizedFailureReason] delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
	[alertView show];
}

- (void)directionsDidUpdateDirections:(UICGDirections *)directions {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	
	// Overlay polylines
	UICGPolyline *polyline = [directions polyline];
	NSArray *routePoints = [polyline routePoints];
	[routeOverlayView setRoutes:routePoints];
	
	// Add annotations
	UICRouteAnnotation *startAnnotation = [[[UICRouteAnnotation alloc] initWithCoordinate:[[routePoints objectAtIndex:0] coordinate]
																					title:@"Punto de partida"
																		   annotationType:UICRouteAnnotationTypeStart] autorelease];
	UICRouteAnnotation *endAnnotation = [[[UICRouteAnnotation alloc] initWithCoordinate:[[routePoints lastObject] coordinate]
																				  title:endPoint.title
																		 annotationType:UICRouteAnnotationTypeEnd] autorelease];
		NSInteger numberOfRoutes = [directions numberOfRoutes];
		for (NSInteger index = 0; index < numberOfRoutes; index++) {
			UICGRoute *route = [directions routeAtIndex:index];
			CLLocation *location = [route endLocation];
			UICRouteAnnotation *annotation = [[[UICRouteAnnotation alloc] initWithCoordinate:[location coordinate]
																					   title:[[route endGeocode] objectForKey:@"address"]
																			  annotationType:UICRouteAnnotationTypeWayPoint] autorelease];
			[routeMapView addAnnotation:annotation];
		}
	
	[routeMapView addAnnotations:[NSArray arrayWithObjects:startAnnotation, endAnnotation, nil]];
}

- (void)directions:(UICGDirections *)directions didFailWithMessage:(NSString *)message 
{
	[self setSearchingModeEnabled:NO];
	
	if (state)
	{
		alertView = [[UIAlertView alloc] initWithTitle:@"Direcciones"
											   message:@"Error al calcular la ruta.\nPor favor inténtelo más tarde"//message
											  delegate:self 
									 cancelButtonTitle:nil 
									 otherButtonTitles:@"OK", nil];
		[alertView show];	
		state = NO;
	}
}

#pragma mark <MKMapViewDelegate> Methods

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
	routeOverlayView.hidden = YES;
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
	routeOverlayView.hidden = NO;
	[routeOverlayView setNeedsDisplay];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
	static NSString *identifier = @"RoutePinAnnotation";
	
	if ([annotation isKindOfClass:[UICRouteAnnotation class]]) {
		MKPinAnnotationView *pinAnnotation = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
		if(!pinAnnotation) {
			pinAnnotation = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier] autorelease];
		}
		
		if ([(UICRouteAnnotation *)annotation annotationType] == UICRouteAnnotationTypeStart) {
			pinAnnotation.pinColor = MKPinAnnotationColorGreen;
		} else if ([(UICRouteAnnotation *)annotation annotationType] == UICRouteAnnotationTypeEnd) {
			pinAnnotation.pinColor = MKPinAnnotationColorRed;
			
		} else {
			pinAnnotation.pinColor = MKPinAnnotationColorPurple;
		}
		
		pinAnnotation.animatesDrop = YES;
		pinAnnotation.enabled = YES;
		pinAnnotation.canShowCallout = YES;
		return pinAnnotation;
	} else {
		return [routeMapView viewForAnnotation:routeMapView.userLocation];
	}
}

- (void)setSearchingModeEnabled:(BOOL)isSearching
{
	//when network action, toggle network indicator and activity indicator
	if (isSearching) {
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		
		UIWindow *window = [UIApplication sharedApplication].keyWindow;
		HUD = [[MBProgressHUD alloc] initWithWindow:window];
		[window addSubview:HUD];
		HUD.labelText = @"Cargando...";
		[HUD show:YES];
	} else {
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
		
		[HUD hide:YES];
		[HUD removeFromSuperview];
		[HUD release];
		HUD = nil;
	}	
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden 
{
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
	HUD = nil;
	[alertView release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{
	[self.navigationController popViewControllerAnimated:YES];
}

@end

